<template>
  <div class="app-container">
    <div
      v-show="
        !detailInfo.visible &&
        !assetCardModifyInfo.visible &&
        !detailListInfo.visible &&
        !modifyStoreInfo.visible &&
        !planDetailInfo.visible
      "
    >
      <!-- 条件栏 -->
      <div class="filter-wrapper">
        <NewPageFilter
          v-model:query="filterInfo.query.queryMap"
          :query-more-json="true"
          :filter-list="filterInfo.searchList"
          :filter-btn="filterInfo.searchBtn"
          :clear-type="clearType"
          :slip-select-request="slipSelectRequest"
        >
        </NewPageFilter>
        <el-button @click="detailListInfo.visible = true">明细页</el-button>
      </div>
      <div class="filter-wrapper">
        <new-page-filter :filter-btn="filterInfo.btnList">
          <template v-slot:filter-print>
            <PopoverPrint
              ref="popoverShow"
              v-model:popoverVisible="popoverVisible"
              :canPrint="true"
              :templateArr="templateArr"
              @tempClick="tempClick"
              @print="handelPrint"
            ></PopoverPrint>
          </template>
          <template v-slot:filter-excel>
            <el-button @click="exportExcel()">导出excel </el-button>
          </template>
        </new-page-filter>
        <div class="display-flex">
          <el-button @click="preferenceInfo.visible = true">偏好设置</el-button>
        </div>
      </div>
      <!-- 表格 -->
      <!--  -->
      <table-container
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="tableInfo.api"
        :query="filterInfo.query"
        :field-list="tableInfo.fieldList"
        :row-class-name="tableRowClassName"
        :handle="tableInfo.handle"
        @pageInfo="pageInfo"
        @sortChange="sortChange"
        @handleEvent="handleEvent"
      >
        <template v-slot:col-orderNo="scope">
          <span class="slip-edit" @click="showDetail(scope.row)">{{
            scope.row.orderNo
          }}</span>
        </template>
        <template v-slot:col-planOrderNo="scope">
          <span class="slip-edit" @click="showPlanDetail(scope.row)">{{
            scope.row.planOrderNo
          }}</span>
        </template>
        <template v-slot:col-assetName="scope">
          <span>{{ scope.row.assetName }}</span>
        </template>
      </table-container>
    </div>
    <SetPreference
      v-if="preferenceInfo.visible"
      v-model:visible="preferenceInfo.visible"
      :search-list="filterInfo.searchList"
      :field-list="tableInfo.fieldList"
      :customize-user-v-o="filterInfo.query.customizeUserVO"
      @callback="setPreferenceCallback"
    />
    <advanced-search
      v-if="advancedSearchInfo.visible"
      v-model:visible="advancedSearchInfo.visible"
      v-model:form-data="advancedSearchInfo.data"
      :field-list="tableInfo.fieldList"
      @callback="advancedSearchCallback"
    />
    <order-detail
      v-if="detailInfo.visible"
      v-model:visible="detailInfo.visible"
      :orderId="detailInfo.id"
      @returnBack="getList"
    />
    <AssetCardModify
      v-if="assetCardModifyInfo.visible"
      v-model:visible="assetCardModifyInfo.visible"
      :title="assetCardModifyInfo.title"
      :type="assetCardModifyInfo.type"
      :current-accounting-interval="
        assetCardModifyInfo.currentAccountingInterval
      "
      :inventoryLocation="assetCardModifyInfo.inventoryLocation"
      :buildCardData="assetCardModifyInfo.buildCardData"
      :id="assetCardModifyInfo.id"
      :fillData="assetCardModifyInfo.fillData"
      @returnModify="getList"
    />
    <detailList
      v-if="detailListInfo.visible"
      v-model:visible="detailListInfo.visible"
      @callback="getList"
    ></detailList>
    <PlanDetail
      v-if="planDetailInfo.visible"
      v-model:visible="planDetailInfo.visible"
      :tableRowId="planDetailInfo.id"
    ></PlanDetail>
    <modifySurplus
      v-if="modifyStoreInfo.visible"
      v-model:visible="modifyStoreInfo.visible"
      :surplusId="modifyStoreInfo.row.id"
      :surplusNo="modifyStoreInfo.row.orderNo"
      :orderId="''"
      type="surplus"
      title="新增入库单"
      @returnModify="getList"
    ></modifySurplus>
    <page-dialog
      v-show="dialogInfo.visible"
      :title="dialogInfo.title"
      v-model:visible="dialogInfo.visible"
      :width="dialogInfo.width"
      :bt-loading="dialogInfo.btLoading"
      :bt-list="dialogInfo.btList"
    >
      <div class="asset-msg">
        <div class="asset-msg-label">
          <i class="el-icon-warning"></i>{{ dialogInfo.msg }}：
        </div>
        <el-radio-group v-model="dialogInfo.flag">
          <el-radio :label="true">当前页数据</el-radio>
          <el-radio :label="false">全部页数据</el-radio>
        </el-radio-group>
      </div>
    </page-dialog>
  </div>
</template>

<script setup name="assetInventorySurplus">
import TableContainer from '@/components/TableContainer/index'
import AssetCardModify from '@/views/asset/assetManage/assetCard/modify'
import SetPreference from '@/components/SetPreference/defaultSetPreference'
import {
  getInventorySurplusOrderCustomizeListPage,
  inventorySurplusOrderValidateCanStore,
  exportInventorySurplusOrder,
  closeInventorySurplusOrder,
} from '@/api/asset.js'
import { getCustomizeSetting, updateUserCustomize } from '@/api/customize'
import { selectByCodeAndDept } from '@/api/report.js'
import { doPrint } from '@/utils/exportUtil.js'
import OrderDetail from './detail'
import PlanDetail from '../assetInventoryPlan/details'
import modifySurplus from '../assetStore/modifySurplus'
const detailList = defineAsyncComponent(() => import('./detailList'))
const { proxy } = getCurrentInstance()
// 过滤相关配置

const dialogInfo = ref({
  visible: false,
  title: '提示',
  btLoading: false,
  type: '',
  msg: '',
  width: '400px',
  flag: true,
  btList: [
    {
      label: '关闭',
      event: handleClose,
      show: true,
    },
    {
      label: '打印',
      type: 'primary',
      event: checkConfirm,
      show: true,
    },
  ],
})
const page = ref({
  curPage: 1, // 当前页
  pageSize: 20, // 每页条数
})
const filterInfo = ref({
  sortArr: [],
  copyQueryMap: {},
  query: {
    sortString: '',
    customizeUserVO: {},
    queryMap: {},
    queryParams: {
      showCanStoreFlag: true,
    },
  },
  searchList: [],
  searchBtn: [
    {
      type: 'button',
      label: '搜索',
      event: search,
    },
    {
      type: 'button',
      label: '高级查询',
      event: advancedSearchShow,
    },
    {
      type: 'button',
      label: '重置',
      event: clearSearch,
    },
  ],
  btnList: [
    {
      type: 'slot',
      value: 'print',
      show: proxy.$permission('assetInventorySurplus:printOrderList'),
    },
    {
      type: 'slot',
      value: 'excel',
      show: proxy.$permission('assetInventorySurplus:excel'),
    },
  ],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  api: undefined,
  selections: [],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '100',
    btList: [
      {
        label: '生成入库单',
        event: modifyStore,
        show: proxy.$permission('assetInventorySurplus:generate'),
        ifRender: function (row) {
          return row.canStoreFlag
        },
      },
      {
        label: '关闭',
        event: close,
        show: proxy.$permission('assetInventorySurplus:close'),
        ifRender: function (row) {
          return row.canStoreFlag
        },
      },
    ],
  },
})
const preferenceInfo = ref({
  visible: false,
})
const advancedSearchInfo = ref({
  visible: false,
  data: {},
})
const detailListInfo = reactive({
  visible: false,
})
const detailInfo = ref({
  visible: false,
  id: '',
})
const planDetailInfo = ref({
  visible: false,
  id: '',
})
const modifyStoreInfo = ref({
  visible: false,
  row: {},
})
const assetCardModifyInfo = ref({
  visible: false,
  title: '',
  id: '',
  currentAccountingInterval: '',
  type: '',
  inventoryLocation: '',
  buildCardData: [],
  fillData: {},
})
const clearType = ref(true)
const slipSelectRequest = ref(true)

const obj = ref({
  orderNo: {
    label: '任务单号',
    value: 'orderNo',
    componentType: 'input',
    type: 'slot',
    show: false,
    hidden: true,
  },
})
tableInfo.value.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj.value),
})
filterInfo.value.searchList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj.value),
})
getCustomize()
function pageInfo(obj) {
  page.value = obj
}
async function setPreferenceCallback(obj) {
  updateUserCustomize(obj.customizeUserVO).then((res) => {
    if (res && res.success) {
      getCustomize(!slipSelectRequest.value)
    }
  })
}
function advancedSearchShow() {
  advancedSearchInfo.value.visible = true
}
async function advancedSearchCallback(obj) {
  filterInfo.value.query.queryMap = {}
  filterInfo.value.query.queryDtoList = [...obj.queryDtoList]
  advancedSearchInfo.value.data = obj.data
  await getList()
  clearType.value = !clearType.value
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(
    filterInfo.value.copyQueryMap
  )
}
// 获取列表
async function getList() {
  tableInfo.value.refresh = Math.random()
}
// 搜索
function search() {
  // 重置分页

  advancedSearchInfo.value.data = {}
  filterInfo.value.query.queryDtoList = []
  tableInfo.value.initCurpage = Math.random()
  tableInfo.value.refresh = Math.random()
}
//生成资产入库单
function modifyStore(row) {
  inventorySurplusOrderValidateCanStore(row.id).then((res) => {
    if (res && res.success) {
      if (res.data) {
        modifyStoreInfo.value.visible = true
        modifyStoreInfo.value.row = row
      } else {
        proxy.$message.error({
          message: '当前盘盈单不能生成资产入库单',
          duration: 3000,
          showClose: true,
        })
      }
    }
  })
}

//关闭
function close(row) {
  inventorySurplusOrderValidateCanStore(row.id).then((res) => {
    if (res && res.success) {
      if (res.data) {
        closeInventorySurplusOrder(row.id).then((resp) => {
          if (resp && resp.success) {
            getList()
          }
        })
      } else {
        proxy.$message.error({
          message: '数据已更新，请刷新页面',
          duration: 3000,
          showClose: true,
        })
      }
    }
  })
}
//展示明细
function showDetail(row) {
  sessionStorage.setItem('storeRowId', row.id)
  detailInfo.value.id = row.id
  detailInfo.value.visible = true
}
function showPlanDetail(row) {
  sessionStorage.setItem('storeRowId', row.id)
  planDetailInfo.value.id = row.planOrderId
  planDetailInfo.value.visible = true
}
function tableRowClassName({ row }) {
  let rowId = sessionStorage.getItem('storeRowId')
  if (rowId && row.id === Number(rowId)) {
    return 'check-row'
  }
  return ''
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}
function clearSearch() {
  clearType.value = !clearType.value
  advancedSearchInfo.value.data = {}
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(
    filterInfo.value.copyQueryMap
  )
  search()
}
function getCustomize(_slipSelectRequest = true) {
  let param = {
    tableKey:
      'assetManageAssetInventorySurplusList-com.slip.spd.entity.vo.asset.AssetInventorySurplusOrderVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.value.query.customizeUserVO = data
      tableInfo.value.fieldList = proxy.$fn.setFieldList(
        tableInfo.value.fieldList,
        data.detail
      )
      let searchInfo = proxy.$fn.setSearchList(
        filterInfo.value.searchList,
        data.detail
      )
      filterInfo.value.query.queryMap = {
        ...searchInfo.queryMap,
        ...filterInfo.value.query.queryMap,
      }
      filterInfo.value.searchList = searchInfo.searchList
      filterInfo.value.searchList.forEach((item) => {
        item.event = search
      })
      filterInfo.value.copyQueryMap = proxy.$fn.deepClone(
        filterInfo.value.query.queryMap
      )
      slipSelectRequest.value = _slipSelectRequest
      tableInfo.value.api = getInventorySurplusOrderCustomizeListPage
      getList()
    }
  })
}
function sortChange(column) {
  if (filterInfo.value.query.customizeUserVO.head.sortType === 0) {
    let arr = proxy.$fn.sortChange(column, filterInfo.value.sortArr)
    filterInfo.value.sortArr = arr
    filterInfo.value.query.sortString = arr.length ? arr.toString() : ''
    getList()
  }
}
function handleClose() {
  dialogInfo.value.visible = false
}
function checkConfirm() {
  if (dialogInfo.value.type === 'excel') {
    exportExcelList()
  } else if ((dialogInfo.value.type = 'print')) {
    print()
  }
  dialogInfo.value.visible = false
  dialogInfo.value.msg = ''
}
function exportExcel() {
  dialogInfo.value.visible = true
  dialogInfo.value.type = 'excel'
  dialogInfo.value.msg = '请选择数据导出范围'
  dialogInfo.value.btList[1].label = '导出'
  dialogInfo.value.flag = true
}
function exportExcelList() {
  let params = {
    ...filterInfo.value.query,
    ...page.value,
    page: dialogInfo.value.flag,
  }
  exportInventorySurplusOrder(params).then((resp) => {
    if (resp) {
      proxy.$fn.parseExcel(resp)
    }
  })
}
function handelPrint() {
  dialogInfo.value.visible = true
  dialogInfo.value.type = 'print'
  dialogInfo.value.msg = '请选择数据打印范围'
  dialogInfo.value.btList[1].label = '打印'
  dialogInfo.value.flag = true
}
const popoverVisible = ref(false)
const templateArr = ref([])
async function print() {
  selectByCodeAndDept({
    tempCode: 'assetInventorySurplus',
  }).then((res) => {
    if (res && res.success) {
      templateArr.value = res.data
      popoverVisible.value = true
      // 一条数据则直接打印
      if (templateArr.value.length === 1) {
        proxy.$refs.popoverShow.hidePopover()
        doPrint({
          name: templateArr.value[0].ureportName,
          params: {},
          callback: printCallback,
          data: {
            customParam: JSON.stringify({
              ...filterInfo.value.query,
              ...page.value,
              page: dialogInfo.value.flag,
            }),
          },
        })
      }
    }
  })
}
function tempClick(item) {
  doPrint({
    name: item.ureportName,
    params: {
      ...filterInfo.value.query,
    },
    callback: printCallback,
    data: {
      customParam: JSON.stringify({
        ...filterInfo.value.query,
        ...page.value,
        page: dialogInfo.value.flag,
      }),
    },
  })
  popoverVisible.value = false
}

function printCallback() {
  try {
  } catch (error) {}
}
</script>

<style scoped></style>
